'use strict';
const path = require('path')
const log = require('@xykj-cli-dev/log')
const Package = require('@xykj-cli-dev/package')
const {exec} = require('@xykj-cli-dev/utils')
const SETTINGS = {
    init:'@imooc-cli/init'
}
const CACHE_DIR = 'dependencies'
let pkg
async function execInstall() {
    let targetPath = process.env.CLI_TARGET_PATH
    const homePath = process.env.CLI_HOME_PATH
    let storePath = ''
    log.verbose('targetPath',targetPath)
    log.verbose('homePath',homePath)
    const cmdObj = arguments[arguments.length-1]
    const cmdName = cmdObj.name()
    const packageName = SETTINGS[cmdName]
    const packageVersion = 'latest'
    console.log('targetPath',targetPath,storePath)
    if(!targetPath){
        targetPath = path.resolve(homePath,CACHE_DIR)
        storePath = path.resolve(targetPath,'node_modules')
        pkg = new Package({
            targetPath,
            storePath,
            packageName,
            packageVersion
        })
        if(await pkg.exists()){
            // 更新package
            await pkg.update()
        }else{
            // 安装package
           await pkg.install()
        }
    }else{
        pkg = new Package({
            targetPath,
            packageName,
            packageVersion
        })
    }
    const rootFile = pkg.getRootFilePath()
    console.log("target",rootFile);
    if(rootFile){
        try{
            // 在当前进程中调用
            // require(rootFile).call(null,Array.from(arguments))
            // 在node子进程中调用
            const args = Array.from(arguments)
            const cmd = args[args.length-1]
            const o = Object.create(null)
            Object.keys(cmd).forEach(key=>{
                if(cmd.hasOwnProperty(key)&&
                    !key.startsWith('_') &&
                    key != 'parent'
                ){
                    o[key] = cmd[key]
                }
            })
            //args[args.length-1] = o
            let tempObject = {
                commands:o.commands,
                args:o.args,
                rawArgs:o.rawArgs,
                processedArgs:o.processedArgs,
                opts:cmd.opts()
            }
            args[args.length-1] = tempObject
            let code = `require('${rootFile}').call(null,${JSON.stringify(args)})`
            const child = exec('node',['-e',code],{
                cwd:process.cwd(),
                stdio:'inherit',
            })
            // 监听命令执行失败
            child.on('error',e=>{
                console.log('指令执行失败'+e.message)
                process.exit(1)
            })
            // 整个命令执行结束后的退出事件
            child.on('exit',e=>{
                console.log("命令执行成功",e)
            })
            //stdio 设置为inherit后，就不需要通过如下方式监听输出了
           /* child.stdout.on('data',(chunk=>{

            }))
            child.stderr.on('data',(chunk=>{

            }))*/
        }catch (e) {
            console.log(e.message)
        }
    }

    //console.log('环境目录',process.env.CLI_HOME_PATH)
    //console.log('动态加载',first,second,three.parent.opts())
}

// function spawn(command,args,options){
//     const win32 = process.platform === 'win32'
//     const cmd = win32 ? 'cmd' : command
//     const cmdArgs = win32 ? ['/c'].concat(command,args) : args
//     return cp.spawn(cmd, cmdArgs, options || {})
// }

module.exports = execInstall;
